package cn.lg.soar.common.util.jackson.serializer;

import cn.lg.soar.common.data.dict.IDict;
import cn.lg.soar.common.util.reflect.ReflectUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.lang.reflect.Field;

/**
 * IDict 序列化
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class EnumSerializer extends JsonSerializer<Enum> {

    public static final EnumSerializer instance = new EnumSerializer();

    private EnumSerializer(){}

    @Override
    public void serialize(Enum e, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        Object currentValue = jsonGenerator.getCurrentValue();
        Field field = ReflectUtil.getField(currentValue.getClass(), jsonGenerator.getOutputContext().getCurrentName());
        Class<?> type = field.getType();
        if (IDict.class.isAssignableFrom(type)) {
            jsonGenerator.writeObject(((IDict)e).getValue());
        } else {
            jsonGenerator.writeString(e.name());
        }
    }
}
